<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html,
    body {
      width: 100vw;
      height: 100vh;
    }

    body {
      background: url("/images/index_bg.jpg") no-repeat center center;
      background-size: cover;
    }

    form {
      width: 30vw;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 20px;
      background-color: #fff;
      border-radius: 30px;
      box-shadow: 2px 2px 2px 1px #ccc;
    }

    form input {
      outline: none;
      border: none;
      background: none;
      font-size: 20px;
      color: #ccc;
      padding: 10px;
      margin: 6px 0;
    }

    form p:last-child {
      display: flex;
      justify-content: center;

    }

    form p:last-child input {
      color: #fff;
      background-color: #f40;
      border-radius: 10%;
    }
  </style>
</head>

<body>
  <form>
    <p>
      <input type="text" placeholder="Name" required pattern="^[A-Za-z]{4,20}$">
    </p>
    <p>
      <input type="password" placeholder="Password" required pattern="^[A-Za-z0-9]{6,20}$">
    </p>
    <p>
      <input type="submit" value="登陆">
    </p>
  </form>
  <script>
    let form = document.getElementsByTagName('form')[0];
    let input = form.getElementsByTagName('input');
    let lock = true;

    form.onsubmit = () => {
      // let data = {uname: input[0].value,upassword: input[1].value};
      let data = `uname=${input[0].value}&upassword=${input[1].value}`
      if (lock) {
        let xhr = new XMLHttpRequest();
        xhr.open("POST", `/login`, true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send(data)
        xhr.onreadystatechange = () => {
          if (xhr.readyState == 4 && xhr.status == 200) {
            if (xhr.responseText == '0') {
              console.log('参数错误')
            } else if (xhr.responseText == '1') {
              alert('登陆成功')
              localStorage.setItem('uname',input[0].value)
              window.location.href = `/home`;
            } else if (xhr.responseText == '3') {
              alert('用户名或者密码不符合规范')
            } else if (xhr.responseText == '2') {
              alert('用户名或者密码错误')
            }
          }
        }
      }

      return false;
    }
  </script>
</body>

</html>